package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.content.ERRORContent;
import com.hmdp.content.LoginContent;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.content.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 发送手机验证码*
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)){
            //如果不符合，返回报信息
            return Result.fail(ERRORContent.PHONE_Error);
        }
        //符合即生成验证码
        String code  = RandomUtil.randomNumbers(6);
        //保存验证码到session
        // session方式存储验证码
//        session.setAttribute(LoginContent.CODE,code);
//        session.setAttribute(LoginContent.PHONE,phone);//以phone 为key不怕用户变动phone
        //redis方式储验证码
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);

        //发送验证码
//        Config config = new Config()
//                // 您的AccessKey ID
//                .setAccessKeyId(LoginContent.ACCESSKEYID)
//                // 您的AccessKey Secret	（这两个还不知道的去我前两次关于阿里云的有教程哪里找）
//                .setAccessKeySecret(LoginContent.ACCESSKEYSECRET);
//        // 访问的域名（这个不用变都是这个）
//        config.endpoint = LoginContent.ENDPOINT;
//        Client client = null;
//        try {
//            client = new Client(config);
//            SendSmsRequest request = new SendSmsRequest();
//
//
//            request.setSignName("阿里云短信测试");//签名名称
//            request.setTemplateCode("SMS_154950909");//模版Code
//            request.setPhoneNumbers("15779299862");//电话号码
//            HashMap<Object, Object> map = new HashMap<>();
//            map.put("code",code);
//            //这里的参数是json格式的字符串
//            request.setTemplateParam(JSONObject.toJSONString(map));
//            SendSmsResponse response = client.sendSms(request);
//            System.out.println("发送成功："+new Gson().toJson(response));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        log.info("发送成功{}",code);
        //ok

        return Result.ok();
    }

    /**
     * 登录功能
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)){
            //如果不符合，返回报信息
            return Result.fail(ERRORContent.PHONE_Error);
        }
        //校验验证码
//        Object code = session.getAttribute(LoginContent.CODE);
        //从redis获取
        String code = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);

        String codeYz = loginForm.getCode();
        if (code == null || !code.equals(codeYz))
        {
            //不一致，报错
            return Result.fail(ERRORContent.CODE_ERROR);
        }

        //一致，根据手机号查询用户
        User user = query().eq(LoginContent.PHONE, phone).one();
        //判断用户是否存在
        if (user == null){
            //不存在创建用户
            user =  createUserByPhone(phone);
        }
        //保存用户信息到session
//        session.setAttribute(LoginContent.USER, BeanUtil.copyProperties(user, UserDTO.class));
        //保存信息到redis
        //随机生成token作为登入令牌
        String token = UUID.randomUUID().toString(true);
        //将user转为Hash存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue) ->fieldValue.toString())
                );
        //存储
        String tokenKey = LOGIN_USER_KEY+token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        //设置时间限制
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL,TimeUnit.MINUTES);
        //返回token
        return Result.ok(token);
    }

    /**
     * 查询用户详情（共同关注）
     * @param userId
     * @return
     */
    @Override
    public Result queryUserById(Long userId) {
        // 查询详情
        User user = getById(userId);
        if (user == null) {
            return Result.ok();
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        // 返回
        return Result.ok(userDTO);
    }

    /**
     * 用户签到
     * @return
     */
    @Override
    public Result sign() {
        //获取登入用户和日期
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        //拼接key
        String key = USER_SIGN_KEY+userId+now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        //获取天数
        int dayOfMonth = now.getDayOfMonth();

        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);


        return Result.ok();

    }

    /**
     * 用户连续签到
     * @return
     */
    @Override
    public Result signCount() {
        //获取登入用户和日期
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        //拼接key
        String key = USER_SIGN_KEY+userId+now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        //获取天数
        int dayOfMonth = now.getDayOfMonth();
        //获取本月至今的签到天数，即一个二进制数
        List<Long> longs = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands
                        .create()
                        .get(BitFieldSubCommands
                                .BitFieldType
                                .unsigned(dayOfMonth)).valueAt(0)
        );
        if (longs == null || longs.isEmpty()){
            return Result.ok(0);
        }
        Long num = longs.get(0);
        if (num == 0||num == null){
            return Result.ok(0);

        }
        //循坏遍历
        int count = 0;
        while (true){
            if ((num & 1) ==0 ){
                break;
            }else {
                count++;
            }
            num >>>= 1;
        }
        //与最后一位数做与运算
        return Result.ok(count);
    }

    /**
     * 通过手机号创建用户
     * @param phone
     * @return
     */
    private User createUserByPhone(String phone) {
        //创建用户
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX+RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
